import { createRouter, createWebHashHistory } from 'vue-router';
import { useNProgress } from '@/utils/progress';
import { useUserStore } from "@/pinia/modules/user";
import { useMobileStore } from '@/pinia/modules/mobile';
import { ElMessage } from "element-plus";
import { store as pinia } from '@/pinia';

const { start, done } = useNProgress();
const routes = [{
  name: 'notfound',
  path: '/:pathMatch(.*)',
  text: '访问地址不存在',
  meta: {
    title: '访问地址不存在',
  },
  component: () => import('@/error/404.vue')
},{
  name: 'mobile',
  path: '/page/:pageId',
  text: '应用',
  meta: {
    title: '应用',
  },
  component: () => import('@/mobile/home/index.vue')
}];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_WEB_PATH || '/'),
  routes
});

const handleKeepAlive = async(to) => {
  if (to.matched.some(item => item.meta.keepAlive)) {
    if (to.matched && to.matched.length > 2) {
      for (let i = 1; i < to.matched.length; i++) {
        const element = to.matched[i - 1];
        if (typeof element.components.default === 'function') {
          await element.components.default();
          await handleKeepAlive(to);
        }
      }
    }
  }
};

let isInitRouter = false;
router.beforeEach(async(to) => {
  start();
  const userStore = useUserStore(pinia);
  to.meta.matched = [...to.matched];
  await handleKeepAlive(to);

  if (userStore.getToken()) {
    if (!isInitRouter) {
      isInitRouter = true;
      await userStore.initUserInfo();
    }
    if (to.path === '/') {
      const mobileStore = useMobileStore(pinia);
      const mobile = await mobileStore.getMobile();
      if (mobile.homeId) {
        return { path: '/page/' + mobile.homeId };
      } else {
        const page = mobile.pageList ? mobile.pageList[0] : null;
        if (page) {
          return { path: '/page/' + page.id };
        } else {
          ElMessage.error("未配置首页！");
          return false;
        }
      }
    } else if (to.matched.length) {
      return true;
    } else {
      return { name: 'notfound' };
    }
  } else {
    const mobileStore = useMobileStore(pinia);
    const mobile = await mobileStore.getMobile();
    if (mobile.loginId) {
      if (to.path === '/page/' + mobile.loginId) {
        return true;
      } else {
        return { path: '/page/' + mobile.loginId };
      }
    } else {
      ElMessage.error("未配置登录页面！");
      return false;
    }
  }
});

router.afterEach(() => {
  done();
});

router.onError(() => {
  done();
});

export default router;
